Ultimate hybrid stack-media automation.md

---
### 1. Which one do I recommend for Social Media Automation?

**The Short Answer:** You **cannot** use just one. You must use a **Hybrid Approach**. 

Social media platforms (Instagram, TikTok, YouTube, X, LinkedIn) have the most aggressive, multi-layered anti-bot detection in the world. 
* If you use **browser-use** alone, its vanilla Playwright backend will leak CDP (Chrome DevTools Protocol) signals, and your account will be shadowbanned or suspended within hours.
* If you use **CloakBrowser/Patchright** alone, you have a stealth browser, but you have to manually code every single click, scroll, and wait-state, which is brittle and breaks the moment the social media site updates its UI.

**The Winning Recommendation:** 
**`browser-use` (The Brain) + `CloakBrowser` or `Patchright` (The Stealth Engine) + Residential Proxies (The Network).**

---
### 2. Playwright vs. browser-use: Which is better?

This is a trick question because **they are not competitors; they are two different layers of the same stack.** 

Think of it like a car:
* **Playwright is the Engine and Steering Wheel.** It is a low-level automation library. You have to write exact code: `page.click('#login_button')`, `page.fill('#password', '123')`. It is 100% deterministic, lightning-fast, and costs $0 in AI tokens. But if Instagram changes the ID of the login button, your code breaks instantly.
* **browser-use is the Self-Driving AI.** It is an *Agent Framework built ON TOP OF Playwright*. You just say: `"Log into Instagram and like the top 3 posts."` The LLM looks at the screen, figures out where the buttons are, and tells Playwright what to click. If Instagram changes its UI, the AI adapts and still finds the button. 

**Verdict:** 
* Use **Playwright** for simple, repetitive, high-speed scraping where the website structure never changes.
* Use **browser-use** for complex, multi-step social media automation where you need the AI to handle popups, CAPTCHAs, dynamic feeds, and unexpected UI changes.

---

### 3. How to Build the Ultimate Hybrid Stack (Step-by-Step)

To get the autonomous intelligence of `browser-use` with the unblockable stealth of `Patchright` (or `CloakBrowser`), you need to swap out the default Playwright engine inside `browser-use` with the stealth engine.

Here is the exact architecture and code to build a **3-Tool Hybrid**:
1. **browser-use** (Autonomous Agent & Memory)
2. **Patchright** (Stealth Drop-in Replacement for Playwright) *(Easier to integrate than CloakBrowser for Python hybrids)*
3. **BrightData / IPRoyal** (Residential Proxies - Mandatory for Social Media)

#### Step 1: Install the Hybrid Dependencies
```bash
pip install browser-use patchright playwright
playwright install chromium
```

#### Step 2: The Master Hybrid Code
This script initializes the stealth browser (Patchright), connects it to residential proxies, and hands the "steering wheel" over to the AI agent (browser-use).

```python
import asyncio
import os
from patchright.async_api import async_playwright
from browser_use import Agent, Browser, BrowserConfig
from langchain_openai import ChatOpenAI

# 1. SETUP YOUR RESIDENTIAL PROXY (CRITICAL FOR SOCIAL MEDIA)
# Never use datacenter IPs for IG/TikTok. Use residential.
PROXY_URL = "http://user:pass@residential-proxy-provider:port"

async def run_hybrid_social_agent():
    # 2. INITIALIZE THE STEALTH BROWSER (Patchright)
    # Patchright bypasses Runtime.enable leaks and basic bot detection
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=False, # Headed mode is safer for social media
            proxy={"server": PROXY_URL},
            args=[
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox"
            ]
        )
        
        # Create a persistent context to save cookies/sessions (Memory)
        context = await browser.new_context(
            viewport={"width": 1920, "height": 1080},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            locale="en-US",
            timezone_id="America/New_York"
        )
        
        # Block images/media to speed up AI processing (optional but saves tokens)
        # await context.route("**/*.{png,jpg,jpeg,gif,svg,mp4}", lambda route: route.abort())

        page = await context.new_page()
        
        # 3. HAND THE STEALTH BROWSER TO BROWSER-USE (The AI Brain)
        # We configure browser-use to use our existing stealth page
        browser_config = BrowserConfig(
            # browser-use allows injecting custom contexts in advanced setups
            # or we just pass the initialized page directly to the agent
        )
        
        llm = ChatOpenAI(model="gpt-4o") # or Claude 3.5 Sonnet
        
        agent = Agent(
            task="""
            Go to instagram.com. 
            Wait for the page to load. If there is a login screen, stop and tell me.
            If I am logged in, search for the hashtag '#AIStartups'.
            Like the first 3 posts, and leave a thoughtful, 1-sentence comment on each 
            about how interesting their technology is.
            Act like a human: wait 3-5 seconds between actions.
            """,
            llm=llm,
            page=page, # <--- INJECTING THE STEALTH PAGE HERE
        )

        print("🤖 AI Agent taking control of Stealth Browser...")
        history = await agent.run()
        
        print("✅ Task Completed. Agent History:")
        print(history)
        
        # Save cookies for next time so you don't have to log in again
        await context.storage_state(path="ig_session.json")
        await browser.close()

asyncio.run(run_hybrid_social_agent())
```

#### Step 3: Upgrading to CloakBrowser (Maximum Stealth)
If Patchright gets detected by TikTok or Instagram's advanced ML, you upgrade the hybrid by swapping Patchright for **CloakBrowser**. 

Instead of `p.chromium.launch()`, you point Playwright to the CloakBrowser executable:

```python
# Using CloakBrowser with browser-use
from playwright.async_api import async_playwright # or patchright
import os

CLOAK_EXECUTABLE = "/path/to/cloakbrowser/chromium"

async with async_playwright() as p:
    browser = await p.chromium.launch(
        executable_path=CLOAK_EXECUTABLE, # <--- C++ PATCHED BINARY
        headless=False,
        args=["--humanize=true"] # CloakBrowser specific flag for mouse/typing behavior
    )
    # ... continue with browser-use agent setup as above ...
```

---
### 🚨 4 Golden Rules for Social Media Automation Survival

Even with the best hybrid stack, social media platforms will ban you if you ignore human behavioral patterns. Give these rules to your AI coder:

1. **The "Warm-Up" Rule:** Never create a brand new account and immediately run an autonomous agent. Accounts need 3–7 days of manual "human" browsing, scrolling, and liking before automation is introduced.
2. **The Proxy-Geo Match:** If your proxy IP is in Germany, but your browser `timezone_id` is set to New York and `locale` is `en-US`, Instagram's security AI will flag you instantly. **Always match Proxy IP location = Browser Timezone = Browser Locale.**
3. **The Jitter Rule:** Humans don't click in 50 milliseconds. Humans scroll past a post, scroll back up, pause for 2.4 seconds, and then click. If you use `CloakBrowser`, always enable `humanize=True`. If using Patchright, inject random `await asyncio.sleep(random.uniform(2.0, 5.5))` between agent actions.
4. **Session Persistence:** Always use `storage_state` to save cookies. Logging in and out repeatedly via automated forms triggers CAPTCHA walls and security checkpoints. Log in once, save the state, and reuse the cookies.
==============================================================

Another combo:
---------------
For social media automation specifically, my pick is **browser-use** as the core, running on **patchright's stealth chromium** as its browser engine, with plain **Playwright** handling the parts that don't need AI at all. Here's why, and how to wire it together.

## Why this combo, not the others

- **Skyvern** is out as the primary tool for this use case for a concrete reason: its anti-bot measures are only available in the managed cloud, not in the open-source repo — so self-hosted, it won't actually help you get past detection on social platforms. Its no-code builder is great for internal enterprise workflows, less so here.
- **CloakBrowser** has real stealth tech, but the free binary is always one release behind, while the actively-patched build sits behind a paid "Pro" tier — you'd be paying a subscription for the version that actually works against current detection.
- **patchright**, by contrast, is fully free, Apache-2.0, and — this is the key fact — browser-use officially documents patchright's chromium as a directly supported browser backend, alongside launching via CDP or a custom executable_path. That's a first-party integration, not a workaround.
- **openbrowser** (ntegrals) is fine but thin, and there are three unrelated same-named repos on GitHub, so it's easy to grab the wrong one.

## Building the hybrid

The trick is not to route *everything* through the LLM. An AI agent is great at handling a page it's never seen before; it's overkill (slower, costs tokens, occasionally wrong) for a login form or an upload button you already know the layout of. So split by predictability, not by tool:Both paths share the same underlying browser session, so cookies, login state, and fingerprint stay consistent no matter which layer is driving.

Setup is three `pip install`s:

```bash
pip install browser-use patchright
patchright install chromium
```

```python
from browser_use import Agent, BrowserSession, ChatAnthropic

# browser-use launches this as its engine instead of vanilla Playwright chromium
browser_session = BrowserSession(
    executable_path="<path patchright installed chromium to>",
    user_data_dir="~/.config/browseruse/profiles/default",  # keeps login sessions
    headless=False,
)

agent = Agent(
    task="Log in and post today's queued caption",
    llm=ChatAnthropic(model="claude-sonnet-5"),
    browser_session=browser_session,
)
```

For the deterministic side, you write ordinary Playwright code against that same session for things you already know the steps to (login, clicking a specific known button) — you only hand control to `agent.run()` for the step where the page layout is unfamiliar or you need it to make a judgment call. Browser-use's own repo has a ready-made example (`examples/browser/stealth.py`) that shows this exact patchright wiring, which is worth pulling up directly since it'll stay current as both projects update.
---------------------------------------------------------------
///\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Kimi-hybrid automation stackstack 
----------------------------------

I'll research the current state of these repos and their alternatives to give you an accurate, up-to-date prioritization and a battle-tested prompt script.
Here's the real 2026 landscape — verified against live repos, benchmarks, and production tests.

---

## 🏆 Prioritized Ranking: Best → Least (Power + Uniqueness)

| Rank | Repo | Stars (Jul 2026) | Why This Rank | Verdict |
|------|------|------------------|---------------|---------|
| **1** | **browser-use/browser-use** | ~97K ⭐ | The most powerful *and* most complete AI browser agent framework. Custom LLM (`bu-ultra`) hits **78% task success** vs ~59% for Claude Opus. CLI 3.0, cloud scaling, stealth browsers, 1000+ integrations. It's the standard other tools compare themselves to. | **The King** |
| **2** | **CloakHQ/CloakBrowser** | ~28K ⭐ | The **most unique** anti-bot solution — not JS patches, a **real custom Chromium binary** with 58+ C++ source-level fingerprint patches. 0.9 reCAPTCHA v3, passes Cloudflare Turnstile, 30/30 detection sites. Nothing else patches at the C++ compiler level. | **The Ghost** |
| **3** | **Skyvern-AI/skyvern** | ~20K ⭐ | Unique **swarm-of-agents** architecture + computer vision comprehension. No brittle selectors — agents reason visually. Enterprise-grade with workflow builder, credential vaults, and speech-to-text. Best for complex multi-step business workflows. | **The Swarm** |
| **4** | **Kaliiiiiiiiii-Vinyzu/patchright** | ~3.2K ⭐ | A solid patched Playwright fork, but 2026 benchmarks show it **underperforms** nodriver and CloakBrowser. It patches CDP leaks (Runtime.enable, Console.enable) but still gets blocked on hard targets like Google Search. Good, not great. | **The Patch** |
| **5** | **ntegrals/openbrowser** | ~500 ⭐ | Lightweight TypeScript agent on Playwright. Clean architecture but **least unique** — it does what browser-use and Stagehand do, with a smaller community and less maturity. Good for quick prototypes. | **The Lightweight** |

---

## 🔄 Better / Easier / Lighter Alternatives

| Repo | Better Alternative | Easier Alternative | Lighter Alternative |
|------|-------------------|-------------------|---------------------|
| **browser-use** | **Skyvern** — better for enterprise workflows with visual reasoning | **Browser Use Cloud** — one API key, no infra setup | **Stagehand** (~23K ⭐) — TypeScript-native, slimmer, great for Cursor/Claude Code |
| **CloakBrowser** | **nodriver** — zero blocked targets in 2026 benchmarks, direct CDP (no Playwright shim) | **SeleniumBase UC Mode** — batteries-included Python, handles CAPTchas out of the box | **Camoufox** — Firefox-based, 0% detection on CreepJS, lighter than patched Chromium |
| **Skyvern** | **browser-use** — higher task success rate, larger ecosystem | **Skyvern Cloud** — managed, no-code workflow builder | **Firecrawl** (~130K ⭐) — if you only need data extraction, not full browser control |
| **patchright** | **nodriver** — beats patchright on every hard target in head-to-head benchmarks | **CloakBrowser** — drop-in Playwright replacement, just swap the import | **playwright-stealth** — lighter JS-injection layer, fine for mid-tier targets |
| **openbrowser** | **Stagehand** — more mature TypeScript agent, better docs, larger community | **Agent Browser** (~35K ⭐) — CLI-first, zero code needed | **browser-use CLI** — `browser-use run "task"` — lighter than writing TypeScript |

---

## 🧠 Full AI Coder Prompt Script

Copy-paste this into your coding agent (Claude Code, Cursor, Codex, etc.). It tells the AI exactly how to architect, integrate, and fallback across these tools.

```markdown
# AI CODER BROWSER AUTOMATION MASTERY GUIDE
## Version: 2026-07-22 | Stack: Python/TypeScript Hybrid

You are a senior browser automation engineer. When building web agents, scraping pipelines, 
or social media automation, you MUST follow this decision tree and integration pattern.

====================================================================
## 1. ARCHITECTURE DECISION TREE (Choose before writing code)
====================================================================

Q1: Is the target protected by Cloudflare, DataDome, reCAPTCHA v3, or bot detection?
    ├── YES → Use CloakBrowser (Python) OR nodriver (Python) as the browser engine
    │         - CloakBrowser: drop-in Playwright, 58 C++ patches, 0.9 reCAPTCHA score
    │         - nodriver: direct CDP, zero blocked in 2026 benchmarks, AGPL license
    │         - NEVER use vanilla Playwright/Puppeteer on anti-bot targets
    │         - ALWAYS pair with residential proxy + humanize=True / behavioral pacing
    │
    └── NO  → Use standard Playwright or browser-use's built-in browser

Q2: Does the task require natural-language reasoning, multi-step planning, or autonomous decision-making?
    ├── YES → Use browser-use (Python) as the agent framework
    │         - Default LLM: ChatBrowserUse(model='bu-ultra') for 78% success rate
    │         - Fallback LLM: ChatBrowserUse(model='anthropic/claude-sonnet-4-6')
    │         - For TypeScript projects: Use Stagehand or Open Browser instead
    │
    └── NO  → Use Skyvern (Python) for deterministic workflows
              - page.act("click login") for natural language actions
              - page.extract() for structured data with JSON schema
              - Better for: forms, downloads, repeated business processes

Q3: Is this a high-volume, repetitive scrape (10K+ pages/day)?
    ├── YES → Use curl_cffi (Python) for HTML-only targets (no JS needed)
    │         - 3.6x faster than browser automation, same TLS fingerprint as Chrome
    │         - Fallback to CloakBrowser + Playwright for JS-heavy pages
    │
    └── NO  → Full browser agent is acceptable

Q4: Do you need persistent memory/context across sessions?
    ├── YES → browser-use: use BrowserProfile with saved cookies/localStorage
    │         - Skyvern: use credential vaults + workflow state
    │         - Open Browser: vector DB integration for long-term context
    │         - ALWAYS save session state to SQLite/Postgres between runs
    │
    └── NO  → Stateless execution is fine

====================================================================
## 2. STEALTH STACK (Mandatory for Social Media / Anti-Bot Targets)
====================================================================

Layer 1: Browser Engine (pick ONE)
  - CloakBrowser: `from cloakbrowser import launch; browser = launch(humanize=True, proxy="...")`
  - nodriver: `import nodriver as uc; browser = await uc.start()`
  - patchright: `from patchright.sync_api import sync_playwright` (only if locked into Playwright)

Layer 2: Proxy (ALWAYS use residential)
  - Rotating residential proxy with geo-targeting
  - Match proxy IP timezone to browser timezone (CloakBrowser: geoip=True)
  - Sticky sessions for login flows (same IP for entire session)

Layer 3: Behavioral Humanization
  - CloakBrowser: `humanize=True` (mouse curves, keyboard timing, scroll patterns)
  - nodriver: built-in behavioral pacing, add random delays between actions
  - Randomize viewport, scroll before clicking, hover before click

Layer 4: Session Persistence
  - Save cookies, localStorage, IndexedDB after login
  - Reuse browser profiles across runs (CloakBrowser Manager for profile isolation)
  - Never create fresh profiles for every run on social platforms

====================================================================
## 3. INTEGRATION PATTERNS
====================================================================

### Pattern A: browser-use + CloakBrowser (Best for AI Agents on Protected Sites)
```python
from browser_use import Agent, BrowserProfile
from cloakbrowser import launch

# Launch stealth browser
browser = launch(humanize=True, proxy="http://user:pass@proxy:8080")

# Connect browser-use to CloakBrowser
agent = Agent(
    task="Post a video to Instagram with caption 'Summer vibes'",
    llm=ChatBrowserUse(model='bu-ultra'),
    browser=browser,  # inject stealth browser
    browser_profile=BrowserProfile(
        headless=False,
        allowed_domains=["*.instagram.com", "*.cdninstagram.com"],
    ),
)
history = await agent.run()
```

### Pattern B: Skyvern Swarm (Best for Enterprise Workflows)
```python
from skyvern import SkyvernClient

client = SkyvernClient(api_key="...")
workflow = await client.create_workflow(
    url="https://example.com/apply",
    steps=[
        {"action": "fill_form", "schema": {"name": "str", "email": "str"}},
        {"action": "upload_file", "field": "resume", "path": "/tmp/resume.pdf"},
        {"action": "click", "target": "Submit button"},
    ]
)
result = await client.run_workflow(workflow.id)
```

### Pattern C: nodriver Direct CDP (Best for Scraping Hard Targets)
```python
import nodriver as uc
import asyncio

async def scrape_protected():
    browser = await uc.start()
    page = await browser.get("https://protected-site.com")
    # nodriver avoids Playwright CDP signatures entirely
    content = await page.get_content()
    await browser.stop()
    return content
```

### Pattern D: TypeScript Lightweight Agent (Best for Node.js projects)
```typescript
// Use Stagehand instead of openbrowser — more mature, better docs
import { Stagehand } from "@browserbasehq/stagehand";

const stagehand = new Stagehand({
  env: "LOCAL",
  headless: false,
});
await stagehand.init();
await stagehand.page.goto("https://example.com");
await stagehand.act({ action: "click the login button" });
```

====================================================================
## 4. ANTI-BOT CHECKLIST (Before shipping ANY automation)
====================================================================

- [ ] Browser passes bot.sannysoft.com, browserscan.net, fingerprintjs.com
- [ ] reCAPTCHA v3 score > 0.7 (test with CloakBrowser or nodriver)
- [ ] Cloudflare Turnstile auto-resolves without manual intervention
- [ ] TLS fingerprint matches real Chrome (check with tls.browserleaks.com)
- [ ] navigator.webdriver === false (not undefined — false)
- [ ] Proxy IP matches browser timezone and locale
- [ ] Mouse movements are curved (not straight lines) with random timing
- [ ] Scroll events precede click events (humans scroll before clicking)
- [ ] Session cookies persist between runs (not fresh every time)
- [ ] Rate limiting: max 1 action per 2-5 seconds with random jitter
- [ ] User-Agent matches browser engine version exactly

====================================================================
## 5. FALLBACK STRATEGY (When primary tool fails)
====================================================================

1. If browser-use fails on a site → Switch to Skyvern (different vision model)
2. If Skyvern fails → Use browser-use Cloud (stealth browsers + proxy rotation)
3. If CloakBrowser gets detected → Switch to nodriver (different control plane)
4. If nodriver fails → Use Camoufox (Firefox TLS fingerprint, different engine)
5. If all browsers fail → Use curl_cffi for API-layer scraping (no browser needed)
6. If rate-limited → Add exponential backoff + proxy rotation + captcha solver (2captcha/anti-captcha)

====================================================================
## 6. SOCIAL MEDIA AUTOMATION RULES
====================================================================

- Instagram/TikTok/YouTube: Use CloakBrowser + residential proxy + saved session
- LinkedIn: Use nodriver (LinkedIn detects Playwright CDP patterns aggressively)
- Twitter/X: browser-use with saved cookies works reliably
- Facebook: Requires persistent profile + humanize=True + slow pacing (5-10s delays)
- NEVER upload files from headless mode on social platforms — use headed mode
- ALWAYS warm up accounts: 3-5 days of passive browsing before posting/engaging

====================================================================
## 7. MEMORY & CONTEXT STRATEGY
====================================================================

Short-term (single session):
  - browser-use: Agent maintains conversation history automatically
  - Skyvern: workflow state object persists across steps
  - Open Browser: contextWindowSize setting (default 128K tokens)

Long-term (across sessions):
  - Save extracted data to SQLite/Postgres with vector embeddings
  - Use LangChain memory or custom vector DB for agent context
  - Store successful workflows as reusable templates in Skyvern
  - Version-control browser profiles (CloakBrowser Manager profiles)


## 8. PERFORMANCE BUDGETS
====================================================================

Tool                | RAM/Instance | Avg Speed | Cost/1K tasks
--------------------|-------------|-----------|---------------
browser-use OSS     | ~400 MB     | Slow      | $0 ( + LLM )
browser-use Cloud   | ~0 MB       | Fast      | ~$0.05/task
Skyvern OSS         | ~350 MB     | Medium    | $0 ( + LLM )
CloakBrowser        | ~200 MB     | Fast      | $0 (Free tier)
nodriver            | ~180 MB     | Fast      | $0
patchright          | ~200 MB     | Medium    | $0
curl_cffi           | ~20 MB      | Fastest   | $0

====================================================================
## 9. QUICK REFERENCE: One-Liners
====================================================================

# Install everything
pip install browser-use cloakbrowser skyvern patchright
pip install nodriver curl_cffi

# Test stealth
python -c "from cloakbrowser import launch; b=launch(); p=b.new_page(); p.goto('https://bot.sannysoft.com'); input('Check results, then press Enter'); b.close()"

# Run browser-use agent
browser-use run "Find the cheapest flight from NYC to London on Google Flights"

# Run Skyvern workflow
skyvern quickstart --postgres

# Test nodriver
python -c "import nodriver as uc, asyncio; asyncio.run(uc.start().get('https://example.com'))"

====================================================================
END OF GUIDE — When in doubt, prefer browser-use for agents, CloakBrowser for stealth, 
and nodriver as the anti-bot fallback. Never build on vanilla Playwright for production 
anti-bot targets in 2026.
```

---

## 💡 Pro Tips

1. **For social media automation**: The winning stack is `browser-use` (agent brain) + `CloakBrowser` (stealth body) + `residential proxy` (identity). This combo passes every major platform's bot detection.

2. **For pure scraping**: Start with `curl_cffi` — if the data is in the HTML, you don't need a browser at all. 3.6x faster, 10x cheaper.

3. **For TypeScript projects**: Skip `openbrowser`. Use **Stagehand** (21K ⭐) — it's more mature, has better error handling, and integrates with Browserbase for cloud scaling.

4. **The 2026 benchmark winner for anti-bot**: **nodriver** had zero blocked targets across 31 production sites, beating CloakBrowser, patchright, and Camoufox. Use it when CloakBrowser fails. 

5. **patchright is declining in value** — benchmarks show it only scores +1 OK vs vanilla Playwright, and fails on the same hard targets (Google Search, canadianinsider). Consider it a stopgap, not a long-term solution. 
============================================================
